# routers/order.py
# 订单与购物车接口
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from schemas import OrderCreate, OrderOut, CartItemOut
from models import Order, CartItem, UserCard
from crud import create_order, add_to_cart
from deps import get_db
from typing import List

router = APIRouter(prefix="/order", tags=["订单"])

@router.post("/add_to_cart", response_model=CartItemOut)
def add_cart(user_id: int, user_card_id: int, quantity: int, db: Session = Depends(get_db)):
    """添加至购物车"""
    return add_to_cart(db, user_id, user_card_id, quantity)

@router.post("/create", response_model=OrderOut)
def create_new_order(order: OrderCreate, buyer_id: int, db: Session = Depends(get_db)):
    """创建订单"""
    user_card = db.query(UserCard).filter(UserCard.id == order.user_card_id).first()
    if not user_card:
        raise HTTPException(status_code=404, detail="商品不存在")
    seller_id = user_card.owner_id
    return create_order(db, order, buyer_id, seller_id, user_card.price)

@router.get("/history/buy/{user_id}", response_model=List[OrderOut])
def get_buy_history(user_id: int, db: Session = Depends(get_db)):
    """查看购买订单历史"""
    return db.query(Order).filter(Order.buyer_id == user_id).all()

@router.get("/history/sell/{user_id}", response_model=List[OrderOut])
def get_sell_history(user_id: int, db: Session = Depends(get_db)):
    """查看销售订单历史"""
    return db.query(Order).filter(Order.seller_id == user_id).all()

@router.get("/cart/{user_id}", response_model=List[CartItemOut])
def get_cart(user_id: int, db: Session = Depends(get_db)):
    """查看用户购物车"""
    return db.query(CartItem).filter(CartItem.user_id == user_id).all() 